<template>
  <div>
    <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"></canvas>
   <button @click="clearCanvas">Clear</button>
    <button @click="saveImage">Save</button>
  </div>
</template>

<script>
export default {
  props: {
    canvasWidth: {
      type: Number,
      default: 400
    },
    canvasHeight: {
      type: Number,
      default: 400
    }
  },
  data() {
    return {
      drawing: false,
      context: null,
      lastX: 0,
      lastY: 0
    };
  },
  mounted() {
    this.context = this.$refs.canvas.getContext('2d');
  },
  methods: {
    handleSignature(dataUrl) {
      // 处理签字数据
      console.log(dataUrl);
    },
    startDrawing(event) {
      this.drawing = true;
      this.lastX = event.clientX - this.$refs.canvas.offsetLeft;
      this.lastY = event.clientY - this.$refs.canvas.offsetTop;
    },
    draw(event) {
      if (!this.drawing) return;
      const x = event.clientX - this.$refs.canvas.offsetLeft;
      const y = event.clientY - this.$refs.canvas.offsetTop;
      this.context.beginPath();
      this.context.moveTo(this.lastX, this.lastY);
      this.context.lineTo(x, y);
      this.context.stroke();
      this.lastX = x;
      this.lastY = y;
    },
    stopDrawing() {
      this.drawing = false;
    },
    clearCanvas() {
      this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    },
    saveImage() {
      const image = this.$refs.canvas.toDataURL();
      // 可以将 image 发送到后端保存或展示
      console.log(image);
    }
  }
};
</script>
